package com.sh.ssao.lottery.config.email;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 发送邮件服务
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender javaMailSender;

    //注入配置文件中配置的信息——>from
    @Value("${spring.mail.from}")
    private  String from;
    @Value("${email.alias}")
    private String alias;
    @Override
    public void sendSimpleMail(String[] to, String subject, String content) {

        try {
            SimpleMailMessage message = new SimpleMailMessage();
            String fromByte = new String((alias + "<" + from + ">").getBytes("UTF-8"));
            //发件人
            message.setFrom(fromByte);
            //收件人
            message.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容
            message.setText(content);
            //发送邮件
            javaMailSender.send(message);
        } catch (MailException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 群发收件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendHtmlMail(String[] to, String subject, String content) {

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message,true);
            String fromByte = new String((alias + "<" + from + ">").getBytes("UTF-8"));
            messageHelper.setFrom(fromByte);
            messageHelper.setTo(to);
            message.setSubject(subject);
            messageHelper.setText("<pre>"+content+"</pre>",true);
            javaMailSender.send(message);
            log.info("邮件已经发送！");
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("发送邮件时发生异常："+e);
        }

    }

    /**
     * 带附件发送邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePath 附件
     */
    @Override
    public void sendAttachmentsMail(String[] to, String subject, String content, String[] filePath) {

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message,true);
            String fromByte = new String((alias + "<" + from + ">").getBytes("UTF-8"));
            messageHelper.setFrom(fromByte);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content,true);
            //携带附件
            for (String s : filePath) {
                if (null!=s && !"".equals(s.trim())){
                    FileSystemResource file = new FileSystemResource(s);
                    /* String fileName = filePath.substring(filePath.lastIndexOf(File.separator));*/
                    String fileName = s.substring(s.lastIndexOf("/")+1);
                    messageHelper.addAttachment(MimeUtility.encodeWord(fileName,"utf-8","B"),file);
                }
            }


            javaMailSender.send(message);
            log.info("邮件加附件发送成功！");
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("发送失败："+e);
        }

    }

    @Override
    public void sendSimpleMailOne(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            String fromByte = new String((alias + "<" + from + ">").getBytes("UTF-8"));
            //发件人
            message.setFrom(fromByte);
            //收件人
            message.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容
            message.setText(content);
            //发送邮件
            javaMailSender.send(message);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("发送邮件时发生异常："+e);
        }
    }

    @Override
    public void sendHtmlMailOne(String to, String subject, String content) {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            String fromByte = new String((alias + " <" + from + ">").getBytes("UTF-8"));
            messageHelper = new MimeMessageHelper(message,true);
            messageHelper.setFrom(fromByte);
            messageHelper.setTo(to);
            message.setSubject(subject);
            messageHelper.setText("<pre>"+content+"</pre>",true);
            javaMailSender.send(message);
            log.info("邮件已经发送！");
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("发送邮件时发生异常："+e);
        }
    }

    @Override
    public void sendAttachmentsMailOne(String to, String subject, String content, String[] filePath) {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message,true);
            String fromByte = new String((alias + "<" + from + ">").getBytes("UTF-8"));
            messageHelper.setFrom(fromByte);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content,true);
            //携带附件
            for (String s : filePath) {
                if (null!=s && !"".equals(s.trim())){
                    FileSystemResource file = new FileSystemResource(s);
                    /* String fileName = filePath.substring(filePath.lastIndexOf(File.separator));*/
                    String fileName = s.substring(s.lastIndexOf("/")+1);
                    messageHelper.addAttachment(MimeUtility.encodeWord(fileName,"utf-8","B"),file);
                }
            }


            javaMailSender.send(message);
            log.info("邮件加附件发送成功！");
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("发送失败："+e);
        }
    }

    /**
     * 异步处理
     * @param to
     * @param subject
     * @param content
     */
    @Async
    @Override
    public void toEmail(String to,String subject,String content){
        log.debug("开始发送email——————————————————————————————————————————");
        this.sendHtmlMailOne(to,subject,content);
        log.debug("结束发送email——————————————————————————————————————————");
    }

    /**
     * 异步处理
     * @param to
     * @param subject
     * @param content
     */
    @Async
    @Override
    public void toEmails(String[] to, String subject, String content){
        log.debug("开始发送email——————————————————————————————————————————");
        this.sendHtmlMail(to,subject,content);
        log.debug("结束发送email——————————————————————————————————————————");
    }
}
